﻿using System.Collections;

namespace DimensionsHelper.LanguageService.Syntax;

public class MetadataListWithAreal<T> : MetadataArealObject, IReadOnlyList<T> where T : SyntaxNode
{
    private SyntaxList<T>? _arealObjects;

    internal MetadataListWithAreal(SyntaxKinds kind, SyntaxNode? parent) :
        base(kind, parent)
    {
    }

    public int Count => _arealObjects?.Count ?? 0;

    public T this[int index]
    {
        get
        {
            if (_arealObjects == null)
            {
                throw new IndexOutOfRangeException(nameof(index));
            }

            return _arealObjects[index];
        }
    }


    public IEnumerator<T> GetEnumerator()
    {
        return _arealObjects == null
            ? Enumerable.Empty<T>().GetEnumerator()
            : _arealObjects.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    /// <summary>
    ///     向集合中添加一个新的元数据对象，此方法会检查节点区间并插入到合适的位置
    /// </summary>
    public void AddArealObject(T obj)
    {
        AddChildMember(ref _arealObjects, obj);
    }


    public override void AcceptVisitor<TV>(SyntaxNodeVisitor<TV> visitor)
    {
        Accept(visitor, AreaName);
        AcceptList(visitor, _arealObjects);
    }
}


public static partial class NodeFactory
{
    internal static TList InitializeMetadataListWithAreal<TList, TElement>(TList list,
        IEnumerable<TElement>? elements)
        where TList : MetadataListWithAreal<TElement>
        where TElement : SyntaxNode
    {
        if (elements == null)
        {
            return list;
        }

        foreach (TElement item in elements)
        {
            list.AddArealObject(item);
        }

        return list;
    }
}